-- Use an on_attach function to only map the following keys
-- after the language server attaches to the current buffer
local lsp_on_attach = function(client, bufnr)
    -- Mappings.
    -- See `:help vim.lsp.*` for documentation on any of the below functions
    local bufopts = { noremap = true, silent = true, buffer = bufnr }
    local km = vim.keymap

    km.set('n', 'gD', vim.lsp.buf.declaration, vim.tbl_extend('keep', bufopts, {desc='LSP 转到声明'}))
    km.set('n', 'gd', vim.lsp.buf.definition, vim.tbl_extend('keep', bufopts, {desc='LSP 转到定义'}))
    km.set('n', 'K', vim.lsp.buf.hover, vim.tbl_extend('keep', bufopts, {desc='LSP 显示光标下的信息'}))
    km.set('n', 'gi', vim.lsp.buf.implementation, vim.tbl_extend('keep', bufopts, {desc='LSP 查找所有实现'}))
    km.set('n', '<C-k>', vim.lsp.buf.signature_help, vim.tbl_extend('keep', bufopts, {desc='LSP 查看签名信息'}))
    km.set('n', '<space>wa', vim.lsp.buf.add_workspace_folder, vim.tbl_extend('keep', bufopts, {desc='LSP 添加工作区目录'}))
    km.set('n', '<space>wr', vim.lsp.buf.remove_workspace_folder, vim.tbl_extend('keep', bufopts, {desc='LSP 删除工作区目录'}))
    km.set('n', '<space>wl', function()
        print(vim.inspect(vim.lsp.buf.list_workspace_folders()))
    end, vim.tbl_extend('keep', bufopts, {desc='LSP 打印所有工作区目录'}))
    km.set('n', '<space>D', vim.lsp.buf.type_definition, vim.tbl_extend('keep', bufopts, {desc='LSP 转到类型定义'}))
    km.set('n', '<space>rn', vim.lsp.buf.rename, vim.tbl_extend('keep', bufopts, {desc='LSP 重命名'}))
    km.set('n', '<space>ca', vim.lsp.buf.code_action, vim.tbl_extend('keep', bufopts, {desc='LSP 重构'}))
    km.set('n', 'gr', vim.lsp.buf.references, vim.tbl_extend('keep', bufopts, {desc='LSP 查看所有引用'}))
    km.set('n', '<space>f', vim.lsp.buf.format, vim.tbl_extend('keep', bufopts, {desc='LSP 格式化'}))
end

return {
    'mason-org/mason-lspconfig.nvim',
    dependencies = {
        { "mason-org/mason.nvim", opts = {} },
        "neovim/nvim-lspconfig",
        'hrsh7th/cmp-nvim-lsp'
    },
    opts = {},
    config = function(_, _)
        require('mason').setup()
        require('mason-lspconfig').setup()

        local cmp_cap = require('cmp_nvim_lsp').default_capabilities()
        vim.lsp.config('*', {
            capabilities = cmp_cap,
            on_attach = lsp_on_attach,
        })
    end
}
